<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <Left />
      </div>
      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国活动断层分布图'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '0px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <OlMap :refId="'disasterLosses'" style="height: 100%" @getMap="getMap" @mapClick="mapClick"></OlMap>
          <MutilLegend
            style="position: absolute; left: 42px; bottom: 150px"
            :titles="legendTitles"
            :items="legendItems"
            :items-per-column="4"
          ></MutilLegend>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">{{ popData.name }}</div>
            </div>
            <div class="popup-content">
              <div class="popup-content-item" v-for="(item, index) in popData.list" :key="index">
                <div>{{ item.key }}：</div>
                <div>{{ item.value }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <Right @changeType="changeType"></Right>
      </div>
    </div>
  </div>
</template>

<script setup name="Index">
import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Text } from 'ol/style';
import Overlay from 'ol/Overlay';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import MutilLegend from '@/components/MutilLegend';
import Left from './index/left/index.vue';
import Right from './index/right/index.vue';
import { getChinaBaseMap, getBaseDir, getGridLayer } from '@/map/projMap.js';
import { useRouter } from 'vue-router';
import { Util } from '@supermap/iclient-ol';
import { ArcgisService } from '@/map/ArcgisService';
import useArcMapDataStore from '@/store/modules/arcMap';
const { getAllArcMapData } = useArcMapDataStore();
import { getfaultNum } from '@/api/activeFault.js';

// 地震个数统计
let totalNum = '1024';
const totalArr = ref([]);
const mapInstance = ref(null);
const vectorLayer = ref(null);
const mapPopupLayer = ref(null);
const provinceFaultLayer = ref(null);
const popupElement = ref();
totalArr.value = Array.from(totalNum);
const chinaBoundFeatures = ref(null);
const chinaProvinceFeatures = ref(null);
const changeTypeData = ref(['晚更新世断层', '早中更新世断层', '前第四纪断层', '全新世断层']);
const popData = reactive({
  name: '',
  list: [
    {
      key: '断层名称',
      value: '',
    },
    {
      key: '活动时代',
      value: '',
    },
    {
      key: '断层性质',
      value: '',
    },
    {
      key: '断层走向',
      value: '0',
    },
    {
      key: '断层倾向',
      value: '0',
    },
    {
      key: '断层长度',
      value: '0',
    },
  ],
});
const legendTitles = [
  { title: '图例', subTitle: '' },
  { title: '断层数量（条）', subTitle: '' },
];
const legendItems = [
  { label: '全新世', color: 'rgba(255,37,37,1)', w: 15, h: 4, r: 10 },
  { label: '晚更新世', color: 'rgba(227,46,255,1)', w: 15, h: 4, r: 10 },
  { label: '早中更新世', color: 'rgba(37,255,130,1)', w: 15, h: 4, r: 10 },
  { label: '前第四纪', color: 'rgba(253,190,65,1)', w: 15, h: 4, r: 10 },
  { label: '>300', color: 'rgba(26,66,194,1)', w: 15, h: 8, r: 0 },
  { label: '150-300', color: 'rgba(48, 96, 255, 1)', w: 15, h: 8, r: 0 },
  { label: '50-150', color: 'rgba(95, 133, 255, 1)', w: 15, h: 8, r: 0 },
  { label: '0-50', color: 'rgba(146, 160, 240, 1)', w: 15, h: 8, r: 0 },
];
// 多选断层
const changeType = (data) => {
  changeTypeData.value = data;
  let mapLyaers = mapInstance.value.getLayers();

  mapLyaers.forEach((layer) => {
    if (layer.get('arcName')) {
      if (changeTypeData.value.includes(layer.get('arcName'))) {
        layer.setVisible(true);
      } else {
        layer.setVisible(false);
      }
    }
  });
};
const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);
  // addProvinceFillLayer();
  // addProvinceNameLayer();
  // addGridLineLayer();
  addProvinceFaultLayer();
  addChinaBound();
  createOverlayLayer();

  //   假数据
  // createVectorLayer();
  // addRandomPoints();
  // setupSelectInteraction();
};
let selectedFeature = null;
const mapClick = async (event) => {
  console.log('event', event);
  if (selectedFeature) {
    // 恢复先前选中要素的样式
    restoreOriginalStyle(selectedFeature);
    selectedFeature = null;
    mapPopupLayer.value.setPosition(undefined);
  }

  const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
  console.log('features--', features);
  if (features.length > 0) {
    // start
    selectedFeature = features.find((feature) => feature.get('FID'));
    if (selectedFeature) {
      let arcgisService = new ArcgisService({});
      let attributes = await arcgisService.getFeatureDataByFid(selectedFeature.get('FID'));
      console.log('attributes---', attributes);
      popData.name = attributes['断层名称'];
      for (let i = 0; i < popData.list.length; i++) {
        const item = popData.list[i];
        item['value'] = attributes[item['key']];
      }

      const newStyle = createNewStyle(selectedFeature);
      selectedFeature.setStyle(newStyle);

      // 获取要素的坐标信息
      popupElement.value.style.display = 'block';
      let coordinate = mapInstance.value.getEventCoordinate(event.originalEvent);
      // 设置弹出框的位置
      mapPopupLayer.value.setPosition(coordinate);
    } else {
      selectedFeature = features.find((feature) => feature.get('level') == 'province');
      if (selectedFeature) {
        let name = selectedFeature.get('name') || '';
        let faultnum = selectedFeature.get('faultNum') || 0;
        goToSecond(name, faultnum);
      }
    }
    return;
    // end
    selectedFeature = features.find((feature) => feature.get('level') == 'province');

    if (!selectedFeature) {
      mapPopupLayer.value.setPosition(undefined);
      return;
    }
    const newStyle = createNewStyle(selectedFeature);
    selectedFeature.setStyle(newStyle);

    // 获取要素的坐标信息
    popupElement.value.style.display = 'block';
    // event.originalEvent.clientX += 20;
    // event.originalEvent.clientY -= 5;
    let coordinate = mapInstance.value.getEventCoordinate(event.originalEvent);
    // 设置弹出框的位置
    mapPopupLayer.value.setPosition(coordinate);
    // 在这里添加处理点击事件的逻辑
    console.log('点击了要素：', selectedFeature.getProperties());
  } else {
    selectedFeature = null;
    mapPopupLayer.value.setPosition(undefined);
  }
};
// 恢复原始样式
const restoreOriginalStyle = (feature) => {
  const originalStyle = createOriginalStyle(feature); // 用于创建原始样式的函数
  feature.setStyle(originalStyle);
};
const createOriginalStyle = (feature) => {
  return new Style({
    stroke: new Stroke({
      color: feature.getStyle().getStroke().getColor(),
      width: 2,
    }),
  });
};
const createNewStyle = (feature) => {
  return new Style({
    stroke: new Stroke({
      color: feature.getStyle().getStroke().getColor(),
      width: 5,
    }),
  });
};
const addProvinceFaultLayer = () => {
  provinceFaultLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(provinceFaultLayer.value);
  addChinaProvinceFeature();
};
const getFaultData = () => {
  getfaultNum().then((res) => {
    let data = res.data;
    let data_0_50 = data[0];
    let data_50_150 = data[1];
    let data_150_300 = data[2];
    let data_300 = data[3];
    if (data_0_50 && data_0_50.length > 0) {
      setProvinceFaultLayer(0, data_0_50);
    }
    if (data_50_150 && data_50_150.length > 0) {
      setProvinceFaultLayer(1, data_50_150);
    }
    if (data_150_300 && data_150_300.length > 0) {
      setProvinceFaultLayer(2, data_150_300);
    }
    if (data_300 && data_300.length > 0) {
      setProvinceFaultLayer(3, data_300);
    }
  });
};
const setProvinceFaultLayer = (type, data) => {
  if (chinaProvinceFeatures.value) {
    data.forEach((item) => {
      let feature = chinaProvinceFeatures.value.find((feature) => {
        if (feature.get('adcode') == item.code) {
          feature.set('faultNum', type);
          return feature;
        }
      });
      if (feature) {
        feature.setStyle(getProviceStyle(type, feature));
      }
    });
  }
};
const getProviceStyle = (type, feature) => {
  var color = {
    0: 'rgba(146, 160, 240, 1)',
    1: 'rgba(95, 133, 255, 1)',
    2: 'rgba(48, 96, 255, 1)',
    3: 'rgba(26, 66, 194, 1)',
  };
  return new Style({
    fill: new Fill({ color: color[type] }),
    stroke: new Stroke({ color: 'rgba(10, 22, 139, 1)', width: 1 }),
    text: new Text({
      font: '10px Calibri,sans-serif',
      fill: new Fill({ color: '#fff' }),
      text: feature.get('name'),
    }),
  });
};
const addChinaProvinceFeature = () => {
  fetch(getBaseDir('china.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      chinaProvinceFeatures.value = geojsonFormat.readFeatures(geojson);
      chinaProvinceFeatures.value.forEach((feature) => {
        feature.setStyle(
          new Style({
            fill: new Fill({ color: 'transparent' }),
            stroke: new Stroke({
              color: 'rgba(10, 22, 139, 1)',
              width: 1,
            }),
            text: new Text({
              font: '10px Calibri,sans-serif',
              fill: new Fill({ color: '#fff' }),
              text: feature.get('name'),
            }),
          })
        );
        // provinceFaultLayer.value.getSource().addFeature(feature);
      });
      provinceFaultLayer.value.getSource().addFeatures(chinaProvinceFeatures.value);
      getFaultData();
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
};

const addChinaBound = () => {
  fetch(getBaseDir('China_4490.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      chinaBoundFeatures.value = geojsonFormat.readFeatures(geojson);
      addArcLayer();
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
};
const addArcLayer = () => {
  if (!chinaBoundFeatures.value) {
    addChinaBound();
  }
  let data = getAllArcMapData;
  if (!data || Array.from(data.keys()).length !== 4) {
    let prom = useArcMapDataStore().getAllArcData();
    prom.then((res) => {
      for (let i = 0; i < changeTypeData.value.length; i++) {
        const name = changeTypeData.value[i];
        let layer = res.get(name);
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, chinaBoundFeatures.value[0]);
      }
    });
  } else {
    for (let i = 0; i < changeTypeData.value.length; i++) {
      const name = changeTypeData.value[i];
      let layer = data?.get(name);
      if (layer) {
        layer.setVisible(true);
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, chinaBoundFeatures.value[0]);
      }
    }
  }
  // let data = useArcMapDataStore().getAllArcData();
  // data.then((res) => {
  //   for (let i = 0; i < changeTypeData.value.length; i++) {
  //     const name = changeTypeData.value[i];
  //     let layer = res.get(name);
  //     mapInstance.value.addLayer(layer);
  //     Util.setMask(layer, chinaBoundFeatures.value[0]);
  //   }
  // });
  return;
  let arcgisService = new ArcgisService({ map: mapInstance.value });
  if (changeTypeData.value.length > 0) {
    for (let i = 0; i < changeTypeData.value.length; i++) {
      let prom = arcgisService.showArcgisHddcLayer(changeTypeData.value[i]);
      prom.then((res) => {
        let layer = res.get(changeTypeData.value[i]);
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, chinaBoundFeatures.value[0]);
      });
    }
  }
};

function addGridLineLayer() {
  fetch(getBaseDir('China_4490.json'))
    .then((response) => response.json()) // 将响应解析为 JSON 数据
    .then((geojson) => {
      // 使用 GeoJSON 格式解析器将数据转换为 Features
      const geojsonFormat = new GeoJSonFormat();
      let features = geojsonFormat.readFeatures(geojson);
      console.log('--feature', features[0]);
      let url = '/iserver/services/map-shpypg/rest/maps/五代图全国断裂';
      getGridLayer(url).then((layer) => {
        mapInstance.value.addLayer(layer);
        Util.setMask(layer, features[0]);
      });
    })
    .catch((error) => {
      console.error('Error fetching or processing GeoJSON:', error);
    });
}

const createOverlayLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};
const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 2,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const addRandomPoints = () => {
  if (!vectorLayer.value) {
    return;
  }
  const provinces = [
    { lonMin: 97.35, lonMax: 108.16, latMin: 26.0, latMax: 34.91 }, // 四川
    { lonMin: 78.0, lonMax: 99.12, latMin: 26.0, latMax: 36.3 }, // 西藏
    { lonMin: 105.66, lonMax: 110.19, latMin: 28.03, latMax: 32.13 }, // 重庆
  ];

  for (let i = 0; i < 100; i++) {
    const province = provinces[Math.floor(Math.random() * provinces.length)];
    const lon = Math.random() * (province.lonMax - province.lonMin) + province.lonMin;
    const lat = Math.random() * (province.latMax - province.latMin) + province.latMin;
    const color = getRandomColor();

    const point = new Feature({
      geometry: new Point([lon, lat]),
    });

    const style = new Style({
      image: new CircleStyle({
        radius: 8,
        fill: new Fill({ color }),
        stroke: null, // 取消边框
      }),
    });

    point.setStyle(style);
    vectorLayer.value.getSource().addFeature(point);
  }
};
const getRandomColor = () => {
  const randomColor = Math.floor(Math.random() * 16777215).toString(16);
  return `#${'0'.repeat(6 - randomColor.length)}${randomColor}`;
};

// 跳转各省局
const router = useRouter();
const goToSecond = (provinceName, num) => {
  router.push({ path: '/activeFault/second', query: { provinceName, num } });
};
</script>

<style scoped lang="scss">
.app-main {
  display: flex;
  justify-content: space-between;

  :deep(.app-left) {
    margin-left: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;
    position: relative;

    .app-left-item {
      flex: auto;
    }
  }

  .app-map {
    width: 960px;
    height: 100%;
    //overflow: hidden; //test
    position: relative;
  }

  :deep(.app-right) {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    .app-right-item {
      flex: auto;
    }
  }

  :deep(.app-left-item) .subheadings + div,
  :deep(.app-right-item) .subheadings + div {
    top: 0 !important;
  }

  :deep(.subheadings) {
    margin-bottom: -35px;
  }
}

/* start */
.popup-bg {
  /* left: 20px; */
  width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      color: #46ffff;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-item {
      display: flex;
      flex-direction: row;
      margin-top: 10px;
    }
  }
}
/* .popup-bg::before {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -43px;
  margin-top: -15px;
  border-color: transparent #0190f9 transparent transparent;
}
.popup-bg:after {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -40px;
  margin-top: -15px;
  border-color: transparent rgba(6, 40, 150) transparent transparent;
} */
:deep(.ol-overlaycontainer-stopevent) {
  z-index: 2;
}
/* end */
</style>
